package client;
import javax.swing.*;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

public class WebGameClient extends JPanel implements MouseListener, ActionListener, KeyListener
{
	// This player
	private int ID = -1;
	private int xPos = 0;
	private int yPos = 0;
	private int xDesired = 0;
	private int yDesired = 0;
	private int width = 10;
	private int height = 10;
	private int score = 0;

	// Logging in
	private JFrame loginFrame;
	private boolean loggedIn = false;
	private JTextField userField;
	private JPasswordField passField;

	// Players
	private Point[] player = new Point[0];

	// Items
	private Point[] item = new Point[0];

	// Output stream
	private ObjectOutputStream out;


	// Start client
	public static void main(String[] args)
	{
		JFrame f = new JFrame();
		f.setSize(705, 725);
		f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setTitle("Game Client");
		f.add(new WebGameClient());
		f.setVisible(true);
	}


	// Constructor
	public WebGameClient()
	{
		try
		{
			Socket socket = new Socket("localhost", 4324);
			Thread t = new Thread(new ClientNetworkInputThread(socket, this));
			t.start();
			out = new ObjectOutputStream(socket.getOutputStream());
		}
		catch(IOException ex)
		{
			System.err.println(ex);
		}
		login();
		addMouseListener(this);
	}


	// Log in client
	public void login()
	{
		// Make login dialog box
		loginFrame = new JFrame("Login");
		loginFrame.setSize(250, 200);
		loginFrame.setAlwaysOnTop(true);
		loginFrame.setResizable(false);
		JPanel loginPanel = new JPanel();
		JLabel promptLabel = new JLabel("Enter your username and password.");
		JLabel userLabel = new JLabel("Username:");
		JLabel passLabel = new JLabel("Password:");
		userField = new JTextField(20);
		passField = new JPasswordField(20);
		JButton loginButton = new JButton("Login");
		loginButton.addActionListener(this);
		FlowLayout layout = new FlowLayout();
		loginPanel.setLayout(layout);
		loginPanel.add(promptLabel);
		loginPanel.add(userLabel);
		loginPanel.add(userField);
		loginPanel.add(passLabel);
		loginPanel.add(passField);
		loginPanel.add(loginButton);
		loginFrame.add(loginPanel);
		loginFrame.setVisible(true);
	}


	// Send password info if login botton is clicked
	public void actionPerformed(ActionEvent e)
	{
		try
		{
			out.writeObject(new ClientRequest(userField.getText(), new String(passField.getPassword())));
		}
		catch(Exception exception)
		{
			exception.printStackTrace();
		}
		loginFrame.setVisible(false);
	}


	// Paint the screen
	public void paintComponent(Graphics g)
	{
		if(loggedIn)
		{
			g.setColor(Color.gray);
			g.fillRect(0, 0, 700, 700);

			// Paint desired position
			g.setColor(Color.red);
			g.fillOval(xDesired-width/2, yDesired-height/2, width, height);

			// Paint all players
			for(int i = 0; i<player.length; i++)
			{
				g.setColor(Color.blue);
				if(player[i].x == xPos && player[i].y == yPos)
				{
					g.setColor(Color.green);
				}
		    	g.fillOval(player[i].x-width/2, player[i].y-height/2, width, height);
			}

			// Paint items
			g.setColor(Color.yellow);
			for(int i = 0; i<item.length; i++)
			{
		    	if(item[i].x != 0 && item[i].y != 0)
		    	{
					g.fillOval(item[i].x-width/2, item[i].y-height/2, width, height);
				}
			}

			// Paint scoreboard
			g.setColor(Color.black);
			g.drawString("Player "+ID, 600, 30);
			g.drawString("Score "+score, 600, 50);
		}
	}


	// Called by ClientNetworkInputThread when the server sends a message
	public void updateClient(ServerResponse response)
	{
		// Store server response
		ID = response.getID();
		score = response.getScore();
		xPos = response.getX();
		yPos = response.getY();
		player = response.getPlayerPositions();
		item = response.getItemPositions();
		// Check to see if server returned a valid ID
		if(ID == -1)  // -1 means login failure - bad user/pass combo
		{
			System.out.println("Log in again");
			login();
		}
		if(ID >= 0)  // Positive ID is good.  -2 is a ping and is ignored
		{
			loggedIn = true;
			repaint();
		}
	}


	// Send a request whenever the user clicks the mouse
	public void mouseReleased(MouseEvent e)
	{
		if(loggedIn)
		{
			xDesired = e.getX();
			yDesired = e.getY();
			try
			{
				out.writeObject(new ClientRequest(xDesired, yDesired));
			}
			catch(Exception exception)
			{
				exception.printStackTrace();
			}
		}
	}
	public void mousePressed(MouseEvent e){}
	public void mouseEntered(MouseEvent e){}
	public void mouseExited(MouseEvent e){}
	public void mouseClicked(MouseEvent e){}


	@Override
	public void keyTyped(KeyEvent e)
	{
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyPressed(KeyEvent e)
	{
		// TODO Auto-generated method stub
		
	}


	@Override
	public void keyReleased(KeyEvent e)
	{
		// TODO Auto-generated method stub
		
	}
}